package com.lagou.java.utils;

import com.lagou.java.annotation.Component;

import java.sql.Connection;
import java.sql.SQLException;

@Component
public class ConnectionUtils {

    private ThreadLocal<Connection> connectionThreadLocal = new ThreadLocal<>();

    //需要单例
    public Connection getCurrentConnection () throws SQLException {
        //判断当前线程中有没有连接, 如果没有绑定, 需要从连接池中获取一个连接绑定到当前线程
        Connection connection = connectionThreadLocal.get();
        if(connection == null) {
            //从连接池获取连接, 并绑定到线程
            connection = DruidUtils.getInstance().getConnection();
            //绑定到当前线程
            connectionThreadLocal.set(connection);
        }
        return connection;
    }

}
